﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using BitwiseOre.Properties;
using BitwiseOre.SharedMemory.Core;
using BitwiseOre.SharedMemory.JetBrains;

namespace BitwiseOre.SharedMemory.Context
{
    [UsedImplicitly]
    internal sealed class StreamConfig : ISemaphoreConfig, IMemoryMappedFileConfig, IConnectionQueuesConfig,
                                         ISharedObjectConfig
    {
        private readonly int _count;
        private readonly int _bufferSize;
        private readonly Guid _guid;
        private readonly IConnectionBuffersSizer _sizer;
        private readonly SharedObjectStatus _status;

        private int _semaphoreNameCount;

        public StreamConfig(IStreamProperties properties, Guid guid, IConnectionBuffersSizer sizer,
                            SharedObjectStatus status)
        {
            if (sizer.IsSizeInvalid(properties.BufferCount, properties.BufferSize))
            {
                var message = Resources.StreamConfig_BufferSizeAndBufferCountTooLarge;
                throw new ArgumentOutOfRangeException("properties",message);
            }
            _count = properties.BufferCount;
            _sizer = sizer;
            _status = status;
            _guid = guid;
            _bufferSize = properties.BufferSize;
        }

        int IConnectionQueuesConfig.BufferSize
        {
            get { return _bufferSize; }
        }

        int IConnectionQueuesConfig.Count
        {
            get { return _count; }
        }

        long IMemoryMappedFileConfig.Capacity
        {
            get { return _sizer.Size(_count, _bufferSize); }
        }

        string IMemoryMappedFileConfig.Name
        {
            get { return string.Format("{0}_mem", _guid); }
        }

        string ISemaphoreConfig.GetName()
        {
            var name = string.Format("{0}_{1}_sem", _guid, _semaphoreNameCount);
            _semaphoreNameCount++;
            return name;
        }

        SharedObjectStatus ISharedObjectConfig.Status
        {
            get { return _status; }
        }
    }
}